import React, {useRef, useState, useEffect} from "react";

interface Label {
    startX: number;
    startY: number;
    endX: number;
    endY: number;
    label: string;
    color: string;
    labelIndex: number;
}

interface CanvasManageProps {
    image: HTMLImageElement | null;
    currentLabel: string;
    labelColors: Map<string, string>;
    onSetLabels: (labels: Label) => void;
    labels: Label[];
}

const CanvasManage: React.FC<CanvasManageProps> = ({image, currentLabel, labelColors, onSetLabels, labels}) => {

    useEffect(() => {
        drawImageAndLabels(image!, labels);
    })

    const canvasRef = useRef<HTMLCanvasElement>(null);

    const [isDrawing, setIsDrawing] = useState(false);
    const [startX, setStartX] = useState(0);
    const [startY, setStartY] = useState(0);
    const drawImageAndLabels = (image: HTMLImageElement | null, labels: Label[]) => {
        const canvas = canvasRef.current;
        if (!canvas) return;
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        // 如果 image 为 null，生成白色背景图
        if (image === null) {
            canvas.width = 512;
            canvas.height = 512;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = '#FFFFFF'; // 设置白色背景
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            return; // 退出函数
        }

        // 确保 canvas 尺寸与图像匹配
        canvas.width = image.width;
        canvas.height = image.height;

        // 绘制图像
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(image, 0, 0, canvas.width, canvas.height);

        // 绘制标签
        labels.forEach(({ startX, startY, endX, endY, label, color }) => {
            ctx.beginPath();
            ctx.strokeStyle = color;
            ctx.lineWidth = 2; // 设置边框宽度
            ctx.rect(startX, startY, endX - startX, endY - startY);
            ctx.stroke();

            // 设置文字样式并绘制文字
            ctx.font = '14px Arial'; // 字体大小和样式
            ctx.fillStyle = color;
            ctx.fillText(label, startX, startY - 5);
        });
    };

    const onMouseDown = (event: React.MouseEvent<HTMLCanvasElement>) => {
        if (image === null) return;
        if (!currentLabel || currentLabel === '') {
            alert('请先选择标签');
            return;
        }
        setIsDrawing(true);
        setStartX(event.nativeEvent.offsetX);
        setStartY(event.nativeEvent.offsetY);
    };

    const onMouseUp = (event: React.MouseEvent<HTMLCanvasElement>) => {
        if (!isDrawing || !image) return;
        setIsDrawing(false);
        const endX = event.nativeEvent.offsetX;
        const endY = event.nativeEvent.offsetY;

        const width = Math.abs(endX - startX);
        const height = Math.abs(endY - startY);

        if (width > 0 && height > 0) {
            onSetLabels({
                startX,
                startY,
                endX,
                endY,
                label: currentLabel,
                color: getColorByLabel(currentLabel),
                labelIndex: getLabelIndex(currentLabel),
            });
        }
    };

    const getColorByLabel = (label: string): string => {
        return labelColors.get(label) || 'black';
    };

    const getLabelIndex = (label: string): number => {
        let index = -1;
        let currentIndex = 0;

        for (const key of [...labelColors.keys()]) {
            if (key === label) {
                index = currentIndex;
                break;
            }
            currentIndex++;
        }
        return index;
    };

    return (
        <canvas
            ref={canvasRef}
            width={image! ? image.width /2 : 0}
            height={image! ? image.height /2 : 0}
            className="border mb-4 mt-1.5"
            onMouseDown={onMouseDown}
            onMouseUp={onMouseUp}
        />
    );
};

export default CanvasManage;
